package com.qianbei.view.transport;

import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;

/**
 * <pre>
 *     author : pwj
 *     e-mail : xxx@xx
 *     time   : 2019/03/12
 *     desc   :
 *     version: 1.0
 * </pre>
 */
public class DecimalInputFilter implements InputFilter {
    private String mRegularExpression;

    public DecimalInputFilter() {
        this(3);
    }
    public DecimalInputFilter(int lastLength) {
        mRegularExpression = String.format("(\\d{1,}(\\.\\d{0,%d})?)", lastLength);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        StringBuilder builder = new StringBuilder(dest);
        if (TextUtils.isEmpty(source)) {
            builder.delete(dstart, dend);
        } else {
            builder.insert(dstart, source);
        }
        String value = builder.toString();
        return value.matches(mRegularExpression) ? null : "";
    }
}
